﻿using System;
using System.ComponentModel;

using NUnit.Framework;

namespace Pvax.Data.Tests
{
    [TestFixture]
    public class TestDbStoreable
    {
        bool changing;

        string changingPropertyName;

        bool changed;

        string changedPropertyName;

        DbStoreable<int> dataObject;

        void ResetFields()
        {
            changing = false;
            changingPropertyName = String.Empty;
            changed = false;
            changedPropertyName = String.Empty;
        }

        void HandlePropertyChanging(object sender, PropertyChangingEventArgs e)
        {
            changing = true;
            changingPropertyName = e.PropertyName;
        }

        void HandlePropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            changed = true;
            changedPropertyName = e.PropertyName;
        }

        [SetUp]
        public void Init()
        {
            ResetFields();
            dataObject = new DbStoreable<int>();
            dataObject.PropertyChanged += new PropertyChangedEventHandler(HandlePropertyChanged);
            dataObject.PropertyChanging += new PropertyChangingEventHandler(HandlePropertyChanging);
        }

        [TearDown]
        public void Done()
        {
            dataObject.PropertyChanged -= new PropertyChangedEventHandler(HandlePropertyChanged);
            dataObject.PropertyChanging -= new PropertyChangingEventHandler(HandlePropertyChanging);
            dataObject = null;
        }

        [Test]
        public void TestChangeNotifications()
        {
            Assert.IsFalse(changing);
            Assert.IsFalse(changed);
            dataObject.Id = 42;
            Assert.IsTrue(changing);
            Assert.IsTrue(changed);
            Assert.AreEqual("Id", changingPropertyName);
            Assert.AreEqual("Id", changedPropertyName);
        }

        [Test]
        public void TestInterface()
        {
            IDbStoreable storeable = dataObject as IDbStoreable;
            Assert.IsNotNull(storeable);
            Assert.IsTrue(storeable.IsNew);
            Assert.IsFalse(storeable.IsDirty);
            dataObject.Id = 42;
            Assert.IsTrue(storeable.IsDirty);
        }
    }
}
